﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoginController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The login controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;
    using Website.CRUDServices;
    using Website.InitializerService;
    using Website.Models;
    using User = Website.Models.Domain.User;

    /// <summary>
    ///     The account controller.
    /// </summary>
    public class AccountController : BaseController
    {
        #region Public Methods and Operators
        /// <summary>
        ///     The index.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult Index()
        {
            FormsAuthentication.SignOut();
            this.Session["LoggedInUser"] = null;
            this.Session.Abandon();
            
            return RedirectToAction("Login");
        }

        /// <summary>
        ///     The login.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult Login(string msg)
        {
            if (msg != null && !string.IsNullOrWhiteSpace(msg))
            {
                ViewData["ErrorMessage"] = msg;
            }

            FormsAuthentication.SignOut();
            this.Session["LoggedInUser"] = null;
            this.Session.Abandon();
            //using (var client = new InitializerServiceClient())
            //{
            //    client.Update();
            //}

            return this.View();
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="username">
        /// The username.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        public ActionResult Login(string username, string password)
        {
            // create a global user object for the logged in user
            var theUser = new User { Username = username, Password = password.Trim() };
            this.Session["LoggedInUser"] = theUser;

            return CRUDServiceProvider.WithCRUDService<ActionResult>(
                client =>
                {
                    var query = new ValidateUserQuery { Username = username, Password = password };

                    IResult res = client.Query(query);

                    if (!(res.GetType() == typeof(ValidateUserResult)))
                    {
                        this.ViewData["ErrorMessage"] = "Brugernavn eller password er forkert.";
                        return this.View();
                    }

                    var result = (ValidateUserResult)client.Query(query);

                    if (result != null && result.InvalidUsernameOrPassword == false && result.UserID != Guid.Empty)
                    {
                        this.Session["UserID"] = result.UserID;

                        var uq = new UsersQuery { Settings = new SearchSettings { IDEquals = result.UserID } };

                        var urs = (UsersResult)client.Query(uq);
                        if (urs.List.Any())
                        {
                            CRUDServices.User serviceUser = urs.List[0];
                            theUser.Name = serviceUser.Name;
                            theUser.PhoneNumber = serviceUser.PhoneNumber;
                            theUser.Username = serviceUser.Username;
                            theUser.Email = serviceUser.Email;
                            theUser.ID = serviceUser.ID;
                            this.Session["LoggedInUser"] = theUser;

                            if( !Roles.IsUserInRole(theUser.ID.ToString(), "User") )
                            {
                                Roles.AddUserToRole(theUser.ID.ToString(), "User");
                            }

                            if (theUser.Username == "admin" || theUser.Username == "s_admin")
                            {
                                FormsAuthentication.SetAuthCookie("admin", false);
                            }
                            else
                            {
                                FormsAuthentication.SetAuthCookie(theUser.ID.ToString(), false);
                            }
                            return RedirectToAction("Index", "Home");
                            
                        }

                    }

                    this.ViewData["ErrorMessage"] = "Brugernavn eller password er forkert.";
                    return this.View();
                });
        }

        public ActionResult Error(ControllerContext context, string aspxerrorpath) 
        {
            this.ViewData["aspxerrorpath"] = HttpUtility.HtmlEncode(aspxerrorpath);

            return View(context);
        }

        [Authorize(Roles = "Admin")]
        public string AddToAdmins(string userName, string password)
        {
            if (!password.Equals("sudo"))
            {
                return "Nothing happened. Wrong password";
            }

            return CRUDServiceProvider.WithCRUDService<string>(
                client =>
                {
                    var result = (UsersResult)client.Query(new UsersQuery
                    {
                        UsernameEquals = userName
                    });

                    if (result != null && result.TotalRowCount > 0)
                    {
                        var id = result.List[0].ID.ToString();

                        if (!Roles.IsUserInRole(id, "Admin"))
                        {
                            Roles.AddUserToRole(id, "Admin");
                        }

                        return "Great success!";
                    }

                    return "An error happened.";
                });

           


            
        }

        #endregion
    }
}